import { Wristband } from "@/entity/wristband.entity";
import { WristbandAdv } from "@/entity/wristband_adv.entity";
import { Repository } from "typeorm";
import { v4 as uuidv4 } from 'uuid';
// 创建手环广播数据
export async function createAdv(
    gw_mac: string,
    mac: string,
    rssi: number,
    data: Partial<WristbandAdv>,
    format: number,
    date: Date,
    wristbandRepo: Repository<Wristband>,
    wristbandAdvRepo: Repository<WristbandAdv>
): Promise<WristbandAdv | undefined> {
    try {
        // 检查 wristband 是否存在
        const existingWristband = await wristbandRepo.findOne({ where: { mac } });
        if (!existingWristband) {
            // 使用 save 方法插入或更新记录
            await wristbandRepo
                .createQueryBuilder()
                .insert()
                .into(Wristband)
                .values({
                    id: uuidv4(),
                    mac,
                    // time: date,
                    time: new Date()
                })
                .orIgnore() // 如果 mac 地址已存在则忽略
                .execute();
            // console.log(`Wristband checked/added with MAC: ${mac}`);
        } else {
            // console.log(`Wristband with MAC: ${mac} already exists.`);
        }

        // 插入 wristbandAdv（无条件新增）
        const newWristbandAdv = {
            gw_mac,
            mac,
            rssi,
            ...data,
            // time: date,
            time: new Date(),
            format
        };

        const savedRecord = await wristbandAdvRepo.save(newWristbandAdv);
        // console.log(`WristbandAdv added with ID: ${savedRecord.id}`);
        return savedRecord;
    } catch (err) {
        console.error('Error occurred while creating wristbandAdv:', err);
        // throw new Error('Failed to create wristbandAdv record');
    }
}
